﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Web;
using System.Data;
using System.Net;
using RegisterationCommon.Student;
using RegisterationCommon.School;
using RegisterationCommon.Education;

namespace RegisterationCommon.Common
{
    /// <summary>
    /// 消息提示类
    /// </summary>
    public static class Message
    {
        #region 客户端消息操作
        /// <summary>
        /// 获取消息提示内容
        /// </summary>
        /// <param name="msgIndex">指定的消息索引</param>
        /// <returns></returns>
        public static string GetMessageContent(int msgIndex)
        {
            XmlDocument doc = Config.Current.GetLanguageDoc();
            XmlElement el = doc.DocumentElement;
            XmlNode msgNode = el.SelectSingleNode(@"message/item[@id='" + msgIndex + "']");

            StringBuilder strMessage = new StringBuilder();
            strMessage.AppendLine("<script type='text/javascript'>");

            switch (msgNode.Attributes["type"].Value)
            {
                case "alter":
                    strMessage.AppendLine("window.alert('" + msgNode.Attributes["text"].Value + "');");
                    strMessage.AppendLine(GetResult(msgNode.Attributes["confirm"].Value, msgNode.Attributes["target"].Value));
                    break;
                case "confirm":
                    strMessage.AppendLine("var msgResult=window.confirm('" + msgNode.Attributes["text"].Value + "');");
                    strMessage.AppendLine("if(msgResult){");
                    strMessage.AppendLine(GetResult(msgNode.Attributes["confirm"].Value, msgNode.Attributes["target"].Value));
                    strMessage.AppendLine("}else{");
                    strMessage.AppendLine(GetResult(msgNode.Attributes["cancel"].Value, msgNode.Attributes["target"].Value));
                    strMessage.AppendLine("}");

                    break;
            }
            strMessage.AppendLine("</script>");

            return strMessage.ToString();
        }

        /// <summary>
        /// 向客户端发送消息内容
        /// </summary>
        /// <param name="msgIndex">指定的消息索引</param>
        /// <returns></returns>
        public static void Send(int msgIndex)
        {
            HttpContext.Current.Response.Write(GetMessageContent(msgIndex));
        }

        public static void Show(string msg)
        {
            HttpContext.Current.Response.Write(msg);
        }

        /// <summary>
        /// 获取消息处理结果
        /// </summary>
        /// <param name="msgResult">消息结果值</param>
        /// <returns></returns>
        private static string GetResult(string msgResult, string target)
        {
            string strResult = "";
            switch (msgResult)
            {
                case "refresh":
                    string currentURL = System.Web.HttpContext.Current.Request.Url.ToString();
                    strResult = (target == "" || target == "self") ? "window.location.href='" + currentURL + "';" : "window." + target + ".location.href='" + currentURL + "';";
                    break;
                case "return":
                    //string fromeURL = System.Web.HttpContext.Current.Request.UrlReferrer.ToString();
                    //strResult = (target == "" || target == "self") ? "window.location.href='" + fromeURL + "';" : "window." + target + ".location.href='" + fromeURL + "';";
                    strResult = (target == "" || target == "self") ? "window.history.go(-2);" : "window." + target + ".history.go(-2);";
                    break;
                case "":
                    strResult = "";
                    break;
                default:
                    if (msgResult.Substring(0, 4) == "url:")
                    {
                        //情况一，msgResult=url:url地址
                        strResult = target == "" ? "window.location.href='" + msgResult.Substring(4) + "';" : "window." + target + ".location.href='" + msgResult.Substring(4) + "';";
                    }
                    else if (msgResult.Substring(0, 3) == "js:")
                    {
                        //情况二，javascript脚本
                        strResult = msgResult.Substring(3);
                    }
                    break;
            }
            return strResult;
        }
        #endregion

        #region 添加操记录
        /// <summary>
        /// 添加历史操作事件记录
        /// </summary>
        /// <param name="eventIndex">指定的事件规则ID</param>
        /// <returns></returns>
        public static bool AddHistoryEvent(int eventIndex)
        {
            return AddHistoryEvent(new RParams(), eventIndex);
        }

        /// <summary>
        /// 添加历史操作事件记录
        /// </summary>
        /// <param name="rp">RParams字典</param>
        /// <param name="eventIndex">指定的事件规则ID</param>
        /// <returns></returns>
        public static bool AddHistoryEvent(RParams rp, int eventIndex)
        {
            try
            {
                XmlDocument doc = Config.Current.GetLanguageDoc();
                XmlElement el = doc.DocumentElement;
                XmlNode eventNode = el.SelectSingleNode(@"event/item[@id='" + eventIndex + "']");

                string preFix = eventNode.Attributes["preFix"].Value;
                string eventInfo = eventNode.Attributes["value"].Value;

                for (int i = 0; i < rp.Items.Count; i++)
                {
                    eventInfo = eventInfo.Replace("{@" + rp.Items[i].ParameterName + "}", rp.Items[i].Value.ToString());
                }

                rp.Items.Clear();
                rp.Add("OptTime", DateTime.Now, SqlDbType.DateTime);
                
                switch (Config.Current.CurrentAccountType)
                {
                    case 0:
                        rp.Add("Operator", StudentInfo.Current.TrueName, SqlDbType.VarChar);
                        break;
                    case 1:
                        rp.Add("Operator", SchoolAccount.Current.AccountName, SqlDbType.VarChar);
                        break;
                    case 2:
                        rp.Add("Operator", EduAccount.Current.AccountName, SqlDbType.VarChar);
                        break;
                }
                
                rp.Add("OptEvent", preFix + ":" + eventInfo, SqlDbType.VarChar);
                IPHostEntry ipe = Dns.GetHostEntry(Dns.GetHostName());
                IPAddress ipa = ipe.AddressList[0];
                rp.Add("OptIP", ipa.ToString(), SqlDbType.VarChar);
                //将事件添加到数据库中
                DBAction.Insert(ETableName.OperateHistory, rp);

                return true;
            }
            catch
            {
                return false;
            }
        }
        #endregion
    }
}
